var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors')

var WebSocket = require('ws');
var url = require('url');
var http = require('http');
var queryString = require('querystring');
var { paperModel } = require('./model/model')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var hwbRouter = require('./routes/hwb')
var lzhRouter = require('./routes/lzh');
var zxrRouter = require('./routes/zxr');
var ljcRouter = require('./routes/ljc');
var ygRouter = require('./routes/yg')
var wjlRouter = require('./routes/wjl')
var lzxRouter = require('./routes/lzx')


var app = express();
app.use(cors())

const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', async (ws, req) => {
  const query = url.parse(req.url).query;
  const params = queryString.parse(query);
  const { sid } = params;
  ws.sid = sid;
  const changeStream = paperModel.watch([{ $match: { 'updateDescription.updatedFields.flag': { $exists: true } } }])
  changeStream.on('change', (change) => {
    if (change.operationType === 'update' && change.updateDescription.updatedFields.flag) {
      wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN && client.sid === sid) {
          client.send(1);
        }
      });
    }
  })
  ws.on('message', async (message, isBinary) => {

  })
  ws.on('close', () => {
    console.log(ws.sid + '断开连接');
    changeStream.close()
    // resultStream.close()
  })
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/lzh', lzhRouter);

app.use('/hwb', hwbRouter);
app.use('/zxr', zxrRouter);
app.use('/ljc', ljcRouter);
app.use('/yg', ygRouter);
app.use('/wjl', wjlRouter);
app.use('/lzx', lzxRouter);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

process.env.PORT = 3001;

server.listen(3003, () => {
  console.log(`Express server is running on port ${3003}`);
});

module.exports = app;

